package com.qunar.tech.team12.shell.command.impl;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.qunar.tech.team12.shell.command.annotation.Cmd;
import com.qunar.tech.team12.shell.command.annotation.Opt;
import com.qunar.tech.team12.shell.exception.ShellException;
import com.qunar.tech.team12.shell.io.Input;
import com.qunar.tech.team12.shell.io.impl.ParamInput;
import com.qunar.tech.team12.shell.io.impl.Pipeline;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by mzy on 14-7-23.
 */

@Cmd(name = "wc")
public class Wc {

    @Opt(shortName = "-l", description = "统计行数")
    public int countLine(Input input) throws ShellException {
        List<String> params = input.read();
        if (params.isEmpty()) {
            throw new ShellException("missing param");
        }

        if (input instanceof ParamInput) {
            return countLineFromFile(params.get(0));
        } else if (input instanceof Pipeline) {
            return countLineFromPipe(params.get(0));
        } else {
            throw new ShellException("no such file " + params.get(0));
        }
    }

    private int countLineFromPipe(String content) {
        int count = 0;
        for (char c : content.toCharArray()) {
            if (c == '\n') {
                count++;
            }
        }
        return count;
    }

    private int countLineFromFile(String s) throws ShellException {
        int count = 0;
        try {
            return Files.asCharSource(new File(s), Charsets.UTF_8).readLines().size();
        } catch (IOException e) {
            throw new ShellException("no such file " + s);
        }
    }
}
